package cn.itsource.zuul1020.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.itsource.basic.domain.JSONResult;
import cn.itsource.basic.util.Constant;
import cn.itsource.domain.login.LoginInfo;
import cn.itsource.util.RedisService;
import cn.itsource.zuul1020.config.RabbitmqConfig;
import cn.itsource.zuul1020.mapper.LoginInfoMapper;
import cn.itsource.zuul1020.service.LoginInfoService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.JSONSerializerMap;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class LoginInfoServiceImpl implements LoginInfoService {
    @Autowired
    LoginInfoMapper loginInfoMapper;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisService redisService;


    @Override
    public JSONResult add(LoginInfo loginInfo) {
        loginInfoMapper.insert(loginInfo);
        Map<String, Object> map = new HashMap<>();
        map.put("phone",loginInfo.getPhone());
        map.put("text",new StringBuilder("[pethome]当前您的登录密码为:").append(loginInfo.getInitPassword()).append(",请您妥善保管").toString());
        String message = JSON.toJSONString(map);
        //todo 统一的发送短信,无论是前端注册还是后台注册,都是统一的,发送的密码 initpassword
        rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPIC_1209, "user.sms", message);
        //通过mq完成发送短信的操作
        return null;
    }

    @Override
    public JSONResult login(LoginInfo loginInfo) {
        LoginInfo exist = loginInfoMapper.login(loginInfo);

        Optional.ofNullable(exist).orElseThrow(() -> new RuntimeException("当前用户不存在"));

        loginInfo.setSalt(exist.getSalt());
        loginInfo.passwordMD5();
        //密码比对
        if (!Objects.equals(loginInfo.getPassword(),exist.getPassword())) throw  new RuntimeException("当前用户不存在");
        //下面就是登录成功的逻辑
        //1.生成uuid
        String uuid = IdUtil.fastSimpleUUID();
        //2.存入redis
        redisService.setStringKeyAndValue(uuid,exist,30);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("token",uuid);
        if (Constant.ONE.equals(exist.getType())) {
            hashMap.put("user", exist);
        }else {
            hashMap.put("employee",exist);
        }

        return JSONResult.success(hashMap);
    }
}
